package com.autoscript.task;

import com.autoscript.ISystemConstant;
import com.autoscript.endpoint.WebSocket;
import com.autoscript.service.RunlogService;
import com.autoscript.utils.SessionMap;
import com.autoscript.utils.WebSocketList;
import com.autoscript.vo.RunlogVo;
import com.dfhc.util.DateUtil;
import com.dfhc.util.FileOperateHelper;
import com.dfhc.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Component
public class SchedulerTask {
    private static Logger logger= LoggerFactory.getLogger(SchedulerTask.class);

    @Autowired
    private RunlogService runlogService;
    @Autowired
    private SessionMap sessionMap;
    @Autowired
    private WebSocketList webSocketList;
    //凌晨1点删除运行日志
    @Scheduled(cron ="0 0 1 * * ? ")
//    @Scheduled(fixedDelay =6000)
    private void removeRunlog(){
        logger.info("removeRunlog");
        Map<String, Object> searchMap = new HashMap<String,Object>();
        List<Map> list = runlogService.search(searchMap);
        String now = DateUtil.getNowDate("yyyy-MM-dd HH:mm:ss");
        RunlogVo runLogVo = new RunlogVo();
        for(Map m:list){
            String startTime = (String) m.get("START_TIME");
            try {
                int days = DateUtil.getDaysBetweenByStr(startTime,now,"yyyy-MM-dd HH:mm:ss");
                //超过1天，删除
                if(days>=1) {

                    //先删除目录
                    String path = FileOperateHelper.getPath((String) m.get("RESULT_FILE"));

                    if(!StringHelper.isEmpty(path)) {
                        //删除目录
                        logger.info("删除目录:"+path);
                        try {
                            FileOperateHelper.delFolder(path);
                        }catch (Exception e){
                            logger.error("删除文件失败",e);
                        }
                    }
                    //后删除记录
                    runLogVo.setId((String) m.get("ID"));
                    logger.info("delete id:"+(String) m.get("ID"));
                    runlogService.delete(runLogVo);
                }
            } catch (Exception e) {
                logger.error("删除日志失败",e);
                e.printStackTrace();
            }
        }
    }
    //每隔2个钟头删除SessionMap,WebSocketList
    @Scheduled(cron ="0 0 0/2 * * ? ")
    private void removeSessionMapWebSocket(){
        Set<String> sessionMapkeys = sessionMap.getKeys();
        Date now = new Date();
        if(!CollectionUtils.isEmpty(sessionMapkeys)) {
            logger.info("before remove sessionMapKeys size:" + sessionMapkeys.size());
            for (String key : sessionMapkeys) {
                Map<String, Object> m = sessionMap.get(key);
                Date createTime = (Date) m.get(ISystemConstant.CREATE_TIME);

                long diffHours = getHoursBetween(DateUtil.toCalendar(now), DateUtil.toCalendar(createTime));
                if (diffHours >= 2) {
                    sessionMap.remove(key);
                }
            }
            logger.info("after remove sessionMapKeys size:" + sessionMap.getKeys().size());
        }else{
            logger.info("sessionMap is empty!");
        }
        //删除过期的WebSocket
        Set<String> webSocketKeys = webSocketList.getKeys();
        if(!CollectionUtils.isEmpty(webSocketKeys)) {
            logger.info("before remove websocketlist size:"+webSocketKeys.size());
            for (String key : webSocketKeys) {
                WebSocket webSocket = webSocketList.get(key);
                long diffHours = getHoursBetween(DateUtil.toCalendar(now), DateUtil.toCalendar(webSocket.getCreateTime()));
                if (diffHours >= 2) {
                    webSocketList.remove(key);
                }
            }
            logger.info("after remove websocketlist size:"+webSocketKeys.size());
        }else{
            logger.info("websocketlist is empty!");
        }
    }

    /**
     * 获取两个日历相差小时数
     * @param d1
     * @param d2
     * @return
     */
    private long getHoursBetween(Calendar d1, Calendar d2) {
        if (d1.after(d2)) {
            Calendar swap = d1;
            d1 = d2;
            d2 = swap;
        }
        long hours = (d2.getTimeInMillis() - d1.getTimeInMillis())
                / (1000 * 60 * 60 );


        return hours;
    }
}
